package com.seeqool.v1;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.SQLException;

import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.border.EtchedBorder;

import com.seeqool.v1.datamodel.SQLTable;

public class DBquery extends JPanel implements QueryCallback, ActionListener{
	private static final long serialVersionUID = 1L;
	private JLabel statusIndicator;
	private Integer queryID;
	private QueryManager queryManager;
	private JButton actionButton;
	private String queryString;
	
	public DBquery(QueryManager dbQueryManager, String SQL) throws SQLException {
		super();
		setLayout(new BorderLayout());
		statusIndicator = new JLabel();
		statusIndicator.setIcon(ImageLibrary.get("loading.gif"));
		statusIndicator.setText(" ");
		actionButton = new IconButton("cancel.png", "Cancel query", this, "Cancel");
		queryManager = dbQueryManager;
		queryString = SQL;
		queryID = dbQueryManager.query(SQL, this, 0)+1;
		MainWindow.addLog("Connection "+queryID.toString()+" - Query: "+SQL);
		JLabel query = new JLabel();
		query.setText(queryString);
		add(statusIndicator, BorderLayout.WEST);
		add(query, BorderLayout.CENTER);
		add(actionButton, BorderLayout.EAST);
		setBorder(new EtchedBorder());
		setBackground(Color.WHITE);
	}

	public void onComplete(int qID) {
		statusIndicator.setIcon(ImageLibrary.get("tick.png"));
		actionButton.setIcon(ImageLibrary.get("chart.png"));
	}

	public void onError(int qID, String queryError) {
		statusIndicator.setIcon(ImageLibrary.get("error.png"));
		actionButton.setIcon(ImageLibrary.get("trash.png"));
		System.out.println(queryError);
	}

	public void onResult(int qID, SQLTable queryResult) {
		try {
			MainWindow.addLog("Connection "+new Integer(queryID).toString()+" - Result");
			ResultPanel rf=new ResultPanel(queryString, queryResult);
			MainWindow.addResultPanel(rf);
			ChartDispatcher.show(rf, queryResult);
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}

	public void onUpdateCount(int qID, int queryUpdates) {
	}

	public void actionPerformed(ActionEvent e) {
		if (queryID>0) {
			queryManager.cancel(queryID-1);
			queryID = 0;
		}
	}
}
